#include "ReLog.hpp"
#include <iostream>
#include <string>
#include <cstring>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static void Usage(const std::string proc)
{
    std::cout<<"Usage:\n\t"<<proc<<" port [ip]"<<std::endl;
}

class UdpServer
{
    public:
    UdpServer(int port,std::string ip="")
    :port_((uint16_t)port),ip_(ip),socket_(-1)
    {};
    ~UdpServer(){};

    public:
    void init()
    {
        //1. 创建套接字
        socket_ = socket(AF_INET,SOCK_DGRAM,0);
        if(socket_<0)
        {
            logMessage(FATAL,"socket:%s:%d",strerror(errno),socket_);
            exit(1);
        }
        logMessage(DEBUG,"socket create success: %d",socket_);
        //填充协议家族，域
        struct sockaddr_in local;//#include <netinet/in.h>
        memset(&local,sizeof(local),0);//?
        local.sin_family=AF_INET;
        local.sin_port = htons(port_);
        // 服务器都必须具有IP地址,"xx.yy.zz.aaa",字符串风格点分十进制 -> 4字节IP -> uint32_t ip
        // INADDR_ANY(0): 程序员不关心会bind到哪一个ip， 任意地址bind，强烈推荐的做法，所有服务器一般的做法
        // inet_addr: 指定填充确定的IP，特殊用途，或者测试时使用，除了做转化，还会自动给我们进行 h—>n
        local.sin_addr.s_addr = ip_.empty()?htonl(INADDR_ANY):inet_addr(ip_.c_str());

        //2. bind
        if(bind(socket_,(const struct sockaddr*)&local,sizeof(local))==-1)
        {
            logMessage(FATAL,"bind: %s:%d",strerror(errno),socket_);
            exit(2);
        }
        logMessage(DEBUG,"socket bind success: %d",socket_);
    }   
    
    void start()
    {
        char inbuffer[1024];
        char outbuffer[1024];
        while(true)
        {
            struct sockaddr_in peer;//输出型参数
            socklen_t len = sizeof(peer);//输入输出型参数
            ssize_t s = recvfrom(socket_,inbuffer,sizeof(inbuffer)-1,0,
                                (struct sockaddr *)&peer,&len);
            if(s>0)
            {
                inbuffer[s]=0;
            }
            else if(s==-1)
            {
                logMessage(WARINING,"recvfrom: %s:%d",strerror(errno),socket_);
                continue;
            }
            // 读取成功的,除了读取到对方的数据，你还要读取到对方的网络地址[ip:port]
            std::string peerIp = inet_ntoa(peer.sin_addr);
            uint32_t peerProt = ntohs(peer.sin_port);
            // 打印出来客户端给服务器发送过来的消息
            logMessage(NOTICE,"[%s:%d]# %s",peerIp,peerProt,inbuffer);
        }
    }
    private:
    uint16_t port_;
    std::string ip_;
    int socket_;
};

// ./udpServer port [ip]
int main(int argc,char* argv[])
{
    if(argc!=2 && argc!=3)
    {
        Usage(argv[0]);
    }
    uint16_t port = atoi(argv[1]);
    std::string ip;
    if(argc==3)
        ip = argv[2];

    UdpServer svr(port,ip);
    svr.init();
    svr.start();
    return 0;
}